//
//  HomeLocationView.swift
//  HomeLocationView
//
//  Created by Ben on 2021/9/18.
//

import Foundation
import SwiftUI
import Alamofire

struct HomeLocationNeedHelp: Codable {
    var titles: [String]
}

struct HomeLocationRoomToLeft: Codable, Identifiable, Hashable {
    
    var id: String = UUID().uuidString
    var title: String
    var iconName: String
}

struct HomeLocationQuickInto: Codable, Hashable {
    var title: String
    var iconName: String
}

enum SearchScope: CaseIterable {
    case all
    case five
    case ten
    case recommend
    
    var value: String {
        
        switch self {
        case .all:
            return "全城"
        case .five:
            return "5km"
        case .ten:
            return "10km"
        case .recommend:
            return "综合推荐"
        }
    }
    
    var title: String {
        switch self {
        case .all:
            return "全城范围"
        case .five:
            return "附近5km"
        case .ten:
            return "附近10km"
        case .recommend:
            return "综合推荐"
        }
    }
}

struct HomeLocationView: View {
    
    @EnvironmentObject var homeVM: HomeViewModel
    @Namespace var animation
    
    let needHelps: [HomeLocationNeedHelp] = [
        
        HomeLocationNeedHelp(titles: ["帮鉴定球鞋", "帮模型涂装"]),
        HomeLocationNeedHelp(titles: ["帮洗车验车", "帮管道维修"]),
        HomeLocationNeedHelp(titles: ["帮上门遛狗", "帮收纳衣柜"]),
    ]
    
    let concurrentPosts: [String] = [
        "didi",
        "hema",
        "kfc",
        "McDonalds",
        "pizza",
        "Startbucks",
        
    ]
    
    let roomsToLetStyle: [HomeLocationRoomToLeft] = [
        
        HomeLocationRoomToLeft(title: "整租", iconName: "xy_currlocation_room_zheng"),
        HomeLocationRoomToLeft(title: "合租", iconName: "xy_currlocation_room_he"),
        HomeLocationRoomToLeft(title: "千元房", iconName: "xy_currlocation_room_qian"),
        HomeLocationRoomToLeft(title: "全部", iconName: "xy_currlocation_room_all"),
        
    ]
    
    let quickIntos: [HomeLocationQuickInto] = [
    
        HomeLocationQuickInto(title: "闲鱼小站", iconName: "xy_currlocation_xz"),
        HomeLocationQuickInto(title: "低价卡券", iconName: "xy_currlocation_kj"),
        HomeLocationQuickInto(title: "数码维修", iconName: "xy_currlocation_3c"),
        HomeLocationQuickInto(title: "衣物洗护", iconName: "xy_currlocation_xh"),
        HomeLocationQuickInto(title: "同城跑腿", iconName: "xy_currlocation_express"),
        HomeLocationQuickInto(title: "演出票务", iconName: "xy_currlocation_joker"),
    ]
    @State var categoryTabViewMinY: CGFloat = 0
    @State var categoryTabViewOffsetY: CGFloat = 0
    @State var currViewMinY: CGFloat = 0
    var body: some View {
        
        
        GeometryReader { proxy in
            ZStack {
                
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(spacing: 10) {
                        
                        // 找人帮忙、找份兼职、附近回收
                        HeaderView()
                            .padding(.horizontal, 16)
                        // 好房出租
                        RoomsToLeftView()
                            .padding(.horizontal, 16)
                        // 闲鱼小站、低价卡券。。。
                        QuickIntoView()
                            .padding(.leading, 16)
                        
                        Divider()
                            .foregroundColor(Color(hex: 0xF7F7F7))
                            .frame(height: 1)
                            .frame(maxWidth: .infinity)
                        
                        GeometryReader { proxy -> AnyView in
                            let minY = proxy.frame(in: .global).minY
                            
                            if categoryTabViewMinY == 0 {
                                categoryTabViewMinY = minY
                            }
                            
                            categoryTabViewOffsetY = minY - categoryTabViewMinY
                            
                            Dlog("===========")
                            
                            return AnyView(
                                CategoryListTabView(categoryList: homeVM.currLocationCategoryList, currCategoryTab: $homeVM.currLocationCategoryCurrTab, currCategoryTabIndex: $homeVM.currLocationCategoryCurrTabIndex, actionViewWidth: 100) {
                                    
                                    Button {
                                        Dlog("显示距离筛选弹窗")
                                        withAnimation {
                                            homeVM.showSearchScope.toggle()
                                        }
                                    } label: {
                                        
                                        HStack(spacing: 0) {
                                            
                                            Divider()
                                                .foregroundColor(Color(hex: 0x8C8C8C))
                                                .frame(width: 1, height: 15)
                                            
                                            Spacer(minLength: 0)
                                            
                                            Text(homeVM.currSearchScope.title)
                                                .font(.system(size: 12, weight: .semibold))
                                                .lineLimit(1)
                                                .layoutPriority(1)
                                            Image(systemName: homeVM.showSearchScope ? "chevron.up" : "chevron.down")
                                                .font(.system(size: 10))
                                                .foregroundColor(Color(hex: 0x8C8C8C))
                                                .padding(.leading, 4)
                                        }
                                        .padding(.leading, 4)
                                        .padding(.trailing, 16)
                                        .frame(width: 100)
                                        .frame(maxHeight: .infinity)
                                        .background(Color.white)
                                        .frame(alignment: .trailing)
                                    }
                                    .buttonStyle(.plain)
                                    
                                }
                            )
                        }
                        .frame(height: 30)
                        
                        Color.pink
                            .frame(height: 1300)
                    }
                }
                
                VStack {
                    
                    ForEach(SearchScope.allCases, id: \.self) { scope in
                        
                        Button {
                            withAnimation {
                                homeVM.currSearchScope = scope
                                homeVM.showSearchScope.toggle()
                            }
                        } label: {
                            HStack {
                                Text(scope.value)
                                
                                Spacer()
                                
                                if homeVM.currSearchScope == scope {
                                    Image(systemName: "checkmark")
                                } else {
                                    Image(systemName: "checkmark")
                                        .hidden()
                                }
                            }
                            .padding(.vertical, 3)
                            .font(.system(size: 12, weight: .semibold))
                            .foregroundColor(.black)
                        }

                        
                    }
                }
                .padding(.top, 20)
                .padding(.bottom, 10)
                .padding(.horizontal, 10)
                .frame(width: 120)
                .background(
                    VStack(spacing: 0) {
                        
                        Canvas { context, size in

                            let width = size.width
                            let height = size.height
                            

                            context.fill(Path { path in

                                // 移动到x: 0, y: 30
                                // 圆角为10
                                // 三角宽度20 高度20
                                path.move(to: CGPoint(x: 0, y: 30))
                                // 绘制左上角的圆角
                                path.addQuadCurve(to: CGPoint(x: 10, y: 10), control: CGPoint(x: 0, y: 10))
                                // 移动到三角的左下角
                                path.addLine(to: CGPoint(x: 70, y: 10))
                                // 移动到三角的顶角
                                path.addLine(to: CGPoint(x: 80, y: 0))
                                // 移动到三角的右下角
                                path.addLine(to: CGPoint(x: 90, y: 10))
                                // 移动到右上角圆角的起始位置
                                path.addLine(to: CGPoint(x: width - 10, y: 10))
                                // 绘制右上角圆角
                                path.addQuadCurve(to: CGPoint(x: width, y: 30), control: CGPoint(x: width, y: 10))
                                path.addLine(to: CGPoint(x: width, y: height - 10))
                                path.addQuadCurve(to: CGPoint(x: width - 10, y: height), control: CGPoint(x: width, y: height))
                                path.addLine(to: CGPoint(x: 10, y: height))
                                path.addQuadCurve(to: CGPoint(x: 0, y: height - 10), control: CGPoint(x: 0, y: height))
                                path.addLine(to: CGPoint(x: 0, y: 30))
                               

                            }, with: .color(.white))
                        }
                    }
                        .shadow(color: .black.opacity(0.2), radius: 10, x: -5, y: -5)
                        .shadow(color: .black.opacity(0.2), radius: 10, x: 5, y: 5)
                )
                .offset(x: 136, y: currViewMinY + categoryTabViewOffsetY)
                .opacity(homeVM.showSearchScope ? 1 : 0)
                
            }
            .onAppear {
                if currViewMinY == 0 {
                    DispatchQueue.main.async {
                        self.currViewMinY = proxy.frame(in: .global).minY
                        Dlog(self.currViewMinY)
                    }
                }
            }
            
        }
        
        
        
        .frame(maxHeight: .infinity, alignment: .top)
        .task {
            
            if homeVM.currLocationCategoryList.count == 0 {
                
                await homeVM.getCurrLocationCategoryList(cityName: "北京")
                homeVM.currLocationCategoryCurrTab = homeVM.currLocationCategoryList.first
            }
            
        }
        
        
    }
    
    private func QuickIntoView() -> some View {
        ScrollView(.horizontal, showsIndicators: false) {
            LazyHGrid(rows: Array(repeating: GridItem(.flexible()), count: 1), spacing: 5) {
                ForEach(quickIntos, id: \.self) { quickInto in
                    
                    VStack(spacing: 10) {
                        Image(quickInto.iconName)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 45, height: 45)
                            .clipShape(Circle())
                        
                        Text(quickInto.title)
                            .font(.system(size: 12, weight: .semibold))
                    }
                    .frame(width: 80, height: 100)
                    .background(
                    
                        Color(hex: 0xF9F9FA)
                            .frame(width: 80, height: 100)
                            .clipShape(RoundedRectangle(cornerRadius: 10))
                    )
                }
                
                VStack {
                    
                }
                .frame(width: 11)
            }
        }
    }
    
    private func RoomsToLeftView() -> some View {
        return ZStack {
            Image("xy_currlocation_room_bg")
                .resizable()
                .aspectRatio(contentMode: .fill)
            
            HStack {
                VStack {
                    HStack() {
                        Text("好房出租")
                            .font(.system(size: 14, weight: .semibold))
                        
                        Text("真是房东 免中介费")
                            .font(.system(size: 12, weight: .semibold))
                            .foregroundColor(Color(hex: 0x0091FF))
                        
                        Spacer()
                    }
                    
                    //
                    Spacer(minLength: 20)
                    
                    HStack {
                        ForEach(roomsToLetStyle, id: \.self) { roomToLeft in
                            VStack(spacing: 2) {
                                Image(roomToLeft.iconName)
                                    .resizable()
                                    .aspectRatio(contentMode: .fill)
                                    .frame(width: 40, height: 40)
                                Text(roomToLeft.title)
                                    .font(.system(size: 12))
                            }
                            .frame(maxWidth: .infinity)
                        }
                    }
                    
                }
                
                ZStack {
                    
                }
                .frame(width: 120)
                .frame(maxHeight: .infinity)
            }
            .padding(15)
            
        }
        
    }
    
    private func HeaderView() -> some View {
        return HStack {
            
            HomeLocationHeaderItemView(title: "找人帮忙", subTitle: "持证服务更靠谱", subTitleColor: Color(hex: 0x2EAE5E), bgColor: Color(hex: 0xF2FAF8)) {
                
                CycleScrollView(scrollDirection: .vertical, showsIndicators: false, dataSource: needHelps, itemLength: 60) { data in
                    VStack(spacing: 8) {
                        
                        HStack {
                            Image(systemName: "speaker.wave.1.fill")
                            Text(data.titles[0])
                        }
                        .font(.system(size: 12))
                        
                        HStack {
                            Image(systemName: "speaker.wave.1.fill")
                            Text(data.titles[1])
                        }
                        .font(.system(size: 12))
                    }
                    .padding(.vertical, 4)
                }
                
            }
            
            HomeLocationHeaderItemView(title: "找份兼职", subTitle: "薪资担保岗位真", subTitleColor: Color(hex: 0xFB9528), bgColor: Color(hex: 0xFBFAF2)) {
                
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 4) {
                    ForEach(concurrentPosts, id: \.self) { imgName in
                        
                        Image(imgName)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 30, height: 30)
                            .clipShape(Circle())
                    }
                }
            }
            
            HomeLocationHeaderItemView(title: "附近回收", subTitle: "免费上门更省心", subTitleColor: Color(hex: 0xFF6136), bgColor: Color(hex: 0xFBF5F5)) {
                VStack {
                    Image("sofa")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                    
                    Text("已有34.5万人用过")
                        .font(.system(size: 12))
                }
            }
        }
        
    }
}
